import 'package:flutter/material.dart';

import '../bloc/scrawl_draw_controller.dart';
import 'scrawl_painter.dart';

const double DEFAULT_STROKE_WIDTH = 20.0;

/// 画笔绘制预览层
class ScrawlWidget extends StatefulWidget {
  final ScrawlDrawController controller;
  final Widget child;

  const ScrawlWidget({Key key, this.controller, this.child}) : super(key: key);

  @override
  State<StatefulWidget> createState() => ScrawlWidgetState();
}

/// 仅持有绘制相关的对象
class ScrawlWidgetState extends State<ScrawlWidget> {
  ScrawlDrawController get drawController => this.widget.controller;

  ScrawlShouldDrawCallback _shouldDrawCallback;
  ScrawlShouldDrawCallback get shouldDrawCallback => _shouldDrawCallback;
  set shouldDrawCallback(ScrawlShouldDrawCallback shouldDrawCallback) {
    if (shouldDrawCallback == null) {
      drawController.shouldDrawCallbacks.remove(_shouldDrawCallback);
    } else {
      drawController.shouldDrawCallbacks.add(shouldDrawCallback);
    }
    _shouldDrawCallback = shouldDrawCallback;
  }

  @override
  void initState() {
    super.initState();
    setState(() {});
    this.shouldDrawCallback = () => setState(() {});
  }

  @override
  void dispose() {
    this.shouldDrawCallback = null;
    super.dispose();
  }

  static const double PREVIEW_SIZE = 90;
  static const double PREVIEW_MARGIN = 16;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: _buildPaintWidget(),
    );
  }

  Widget _buildPaintWidget() {
    Widget widget;
    widget = drawController.enableTouch
        ? Container(child: this.widget.child)
        : Container();

    widget = CustomPaint(
      painter: ScrawlPainter((canvas, size) {
        // canvas.save();
        drawController.penHistoryForEach((pen, index) {
          pen?.draw(canvas);
        });
        // canvas.restore();
      }),
      child: widget,
    );

    return widget;
  }
}
